<template>
  <div class="container">
    <div class="app-container">
      <el-card>
        <template #header>
          <span>{{ handleTitle }}</span>
        </template>
        <el-form
          label-position="right"
          label-width="120px"
          :model="form"
          :rules="rules"
          ref="addForm"
        >
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.subjectID"
              @change="handleChange"
            >
              <el-option
                :label="item.subjectName"
                :value="item.id"
                v-for="item in subjectsList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.catalogID"
            >
              <el-option
                :label="item.directoryName"
                :value="item.id"
                v-for="item in catalogList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.enterpriseID"
            >
              <el-option
                :label="item.company"
                :value="item.id"
                v-for="item in companysList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select
              placeholder="请选择"
              style="width: 198px; margin-right: 4px"
              v-model="form.province"
              @change="handleChangeCity"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in provincesList"
                :key="item"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择"
              style="width: 198px"
              v-model="form.city"
              @change="handleclearValidate"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in citysList"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.direction"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in directionList"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="form.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <!-- 富文本编辑器 -->
            <quill-editor
              ref="questionQuill"
              v-model="form.question"
              :options="editorOption"
              @change="questionChange"
            />
          </el-form-item>
          <!-- 单选 -->
          <el-form-item label="选项：">
            <el-radio-group
              class="form-item"
              v-model="radioItem"
              v-for="(item, index) in form.options"
              :key="item.code"
              @change="handleRadioOne"
              @click="addImg(index)"
              v-if="form.questionType === '1'"
            >
              <el-radio :label="item.code" v-model="item.isRight"></el-radio>
              <el-input
                style="width: 240px"
                placeholder=""
                v-model="item.title"
              />
              <div class="uploadImg">
                <span
                  @click="handleUpload(index)"
                  :class="{ opacity: item.img }"
                  >上传图片</span
                >
                <img
                  :src="item.img"
                  alt=""
                  class="imgbox"
                  @change="uploadFile($event, index)"
                  :class="{ opacity: !item.img }"
                />
                <input
                  @change="uploadFile($event, index)"
                  ref="uploadBtn"
                  type="file"
                  accept="image/*"
                  hidden
                />
                <i class="el-icon-circle-close" @click="delImg(index)"></i>
              </div>
            </el-radio-group>
            <el-checkbox-group
              class="form-item"
              v-for="(item, index) in form.options"
              :key="item.code"
              v-model="checkboxList"
              @change="handleChenckbox"
              @click="addImg(index)"
              v-if="form.questionType === '2'"
            >
              <el-checkbox :label="item.code" v-model="item.isRight">{{
                item.code
              }}</el-checkbox>
              <el-input
                style="width: 240px"
                placeholder=""
                v-model="item.title"
              />
              <div class="uploadImg">
                <span
                  @click="handleUpload(index)"
                  :class="{ opacity: item.img }"
                  >上传图片</span
                >
                <img
                  :src="item.img"
                  alt=""
                  class="imgbox"
                  @change="uploadFile($event, index)"
                  :class="{ opacity: !item.img }"
                />
                <input
                  @change="uploadFile($event, index)"
                  ref="uploadBtn"
                  type="file"
                  accept="image/*"
                  hidden
                />

                <i class="el-icon-circle-close" @click="delImg(index)"></i>
              </div>
            </el-checkbox-group>

            <el-button
              size="small"
              type="danger"
              :disabled="form.questionType === '1'"
              @click="handleAddItem"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item label="解析视频：">
            <el-input style="width: 240px" v-model="form.videoURL"></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <!-- 富文本编辑器 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="form.answer"
              :options="editorOption"
              @change="answerChange"
            />
          </el-form-item>
          <el-form-item label="题目备注：">
            <el-input
              type="textarea"
              style="min-height: 33px; width: 400px"
              rows="4"
              v-model="form.remarks"
            ></el-input>
          </el-form-item>
          <el-form-item label="试题标签：">
            <el-select
              placeholder="请选择试题标签"
              style="width: 400px"
              v-model="form.tags"
              multiple

            >
              <el-option
                :label="item.tagName"
                :value="item.tagName"
                v-for="item in tagsList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :type="form.id ? 'success' : 'primary'" @click="handleSubmit">{{handleBtnText}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { list as reqSubjectsList } from '../../api/hmmm/subjects'
import { list as reqDirectorysList } from '../../api/hmmm/directorys'
import { list as reqTagsList } from '../../api/hmmm/tags'
import { list } from '../../api/hmmm/companys'
import { provinces, citys } from '../../api/hmmm/citys'
import { direction } from '../../api/hmmm/constants'
import { add, update, detail } from '../../api/hmmm/questions'

import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)

const cos = new COS({
  SecretId: 'AKIDTlpdCWbQ5WjhPs65oIacPyIOEpCLFtJV', // 身份识别ID
  SecretKey: 'ziCSSDjz0pQnvoSq0uZy84kBMIzSghTz' // 身份秘钥
})
export default {
  components: {
    quillEditor
  },
  async created () {
    this.getSubjects()
    this.getCompanysList()
    this.getProvincesList()
    if (this.$route.query.id) {
      const { data } = await detail({ id: this.$route.query.id })
      this.sortCode(data.options)
      this.changeIsRight(data)
      this.handleChange()
      this.form = {
        ...data,
        tags: data.tags ? data.tags.split(',') : ''
      }
    }
  },
  data () {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            ['image', 'link'] // 上传图片、上传视频
          ]
        },
        placeholder: ''
      },
      form: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'A',
            title: '',
            img: '',
            isRight: ''
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'B',
            title: '',
            img: '',
            isRight: ''
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'C',
            title: '',
            img: '',
            isRight: ''
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'D',
            title: '',
            img: '',
            isRight: ''
          }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: []
      },
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: ['blur', 'change']
          }
        ],
        catalogID: [{ required: true, message: '请选择目录', trigger: ['blur', 'change'] }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        city: [{ required: true, message: '请选择地区', trigger: ['blur', 'change'] }],
        direction: [{ required: true, message: '请选择方向', trigger: ['blur', 'change'] }],
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: ['blur', 'change'] }
        ],
        question: [{ required: true, message: '请输入题干', trigger: ['blur', 'change'] }],
        answer: [
          {
            required: true,
            message: '请输入题干',
            trigger: ['blur', 'change']
          }
        ]
      },
      params: {
        page: 1,
        pagesize: 999
      },
      subjectsList: [],
      catalogList: [],
      tagsList: [],
      companysList: [],
      provincesList: [],
      citysList: [],
      directionList: direction,
      checkboxList: [],
      radioItem: '',
      // 是否有文件
      watchFile: '',
      percentage: 0
    }
  },
  watch: {
    'form.questionType': {
      handler (newVal) {
        if (this.form.id) return
        if (newVal === '1' || newVal === '2') {
          this.form.options = [
            {
            // 代码  标题  图片URL  是否正确答案
              code: 'A',
              title: '',
              img: '',
              isRight: false
            },
            {
            // 代码  标题  图片URL  是否正确答案
              code: 'B',
              title: '',
              img: '',
              isRight: false
            },
            {
            // 代码  标题  图片URL  是否正确答案
              code: 'C',
              title: '',
              img: '',
              isRight: false
            },
            {
            // 代码  标题  图片URL  是否正确答案
              code: 'D',
              title: '',
              img: '',
              isRight: false
            }
          ]
        }
        this.radioItem = ''
        this.checkboxList = []
      }
    }
  },
  methods: {
    // 处理答案对错
    changeIsRight (obj) {
      // 处理答案对错
      const rightArr = []
      obj.options.forEach(item => { if (item.isRight) rightArr.push(item.code) })
      if (rightArr.length > 1) {
        this.checkboxList = [...rightArr]
      } else {
        this.radioItem = rightArr[0]
      }
    },
    sortCode (arr) {
      arr.sort((a, b) => {
        return a.code < b.code ? -1 : 1
      })
    },
    // 富文本编辑
    questionChange () {
      this.$refs.addForm.clearValidate('question')
    },
    answerChange () {
      this.$refs.addForm.clearValidate('answer')
    },
    // 获取学科列表
    async getSubjects () {
      const { data } = await reqSubjectsList(this.params)
      this.subjectsList = data.items
    },
    // 学科联动目录、标签
    async handleChange (val) {
      // 目录
      if (!this.form.id) this.form.catalogID = ''
      const { data } = await reqDirectorysList({ subjectID: val })
      this.catalogList = data.items

      // 标签
      if (!this.form.id) this.form.tags = ''
      const subjectID = this.form.subjectID
      const { data: tags } = await reqTagsList({ ...this.params, subjectID })
      this.tagsList = tags.items
    },
    // 获取公司列表表
    async getCompanysList () {
      const { data } = await list(this.params)
      this.companysList = data.items
    },
    // 获取城市
    getProvincesList () {
      const res = provinces()
      this.provincesList = res
    },
    // 市区联动
    handleChangeCity () {
      this.form.city = ''
      const res = citys(this.form.province)
      this.citysList = res
      if (this.form.city === '') {
        this.$refs.addForm.validateField('city')
      }
    },
    // 选择市区移除校验
    handleclearValidate () {
      this.$refs.addForm.clearValidate('city')
    },
    // 单选
    handleRadioOne () {
      this.form.options.forEach(item => {
        item.isRight = item.code === this.radioItem
      })
    },
    // 多选
    handleChenckbox () {
      this.form.options.forEach(item => {
        item.isRight = this.checkboxList.includes(item.code)
      })
    },
    // 添加答案
    handleAddItem () {
      // code是字母 例如code是C
      const code = this.form.options[this.form.options.length - 1].code
      // 字母转数字 假设对应数字是60
      const num = code.charCodeAt(0)
      const obj = {
        // 字母转数字  数字+1得到后一位字母 60+1转成字母得到D
        code: String.fromCharCode(num + 1),
        title: '',
        img: '',
        isRight: false
      }
      this.form.options.push(obj)
    },
    // 提交
    handleSubmit () {
      this.$refs.addForm.validate(async boo => {
        if (!boo) return this.$message.error('请按规则填写')
        console.log(this.$refs.uploadBtn[0].files.length === 0)
        const obj = {}
        if (this.form.tags) {
          obj.tags = this.form.tags.join(',')
        }
        if (this.form.id) {
          const res = await update({ ...this.form, ...obj })
          console.log(res)
        } else {
          const res = await add({ ...this.form, ...obj })
          console.log(res)
        }
        this.$message.success(`${this.form.id ? '修改' : '添加'}成功`)
        this.clearForm()
        this.$router.push('/questions/list')
      })
    },
    // 答案 - 点击上传图片
    handleUpload (index) {
      this.$refs.uploadBtn[index].click()
    },
    // 缩略图
    uploadFile (event, index) {
      const files = event.target.files
      this.watchFile = files
      const file = this.form.options[index]
      if (!files[0]) return
      // 预览图
      // const url = URL.createObjectURL(event.target.files[0])
      const isLM2M = files[0].size / 1024 / 1024 < 2
      if (!isLM2M) return this.$message.error('图片不能大于2M')
      cos.putObject({
        Bucket: 'hrsass-1312779691', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: 'team-combat' + parseInt(Math.random() * 99999) + event.target.files[0].name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: event.target.files[0] // 上传文件对象
      }, (err, data) => {
        if (err) this.$message.error('上传文件失败')
        this.watchFile = ''
        file.img = 'https://' + data.Location
      })
    },
    // 删除图片
    delImg (index) {
      this.form.options[index].img = ''
    },
    clearForm () {
      this.$refs.addForm.resetFields()
      this.form = {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            // 代码  标题  图片URL  是否正确答案
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      }
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    },
    handleTitle () {
      return this.form.id ? '试题修改' : '试题录入'
    },
    handleBtnText () {
      return this.form.id ? '确认修改' : '确认提交'
    }
  },
  mounted () {
    // console.log('this is current quill instance object', this.editor)
  }
}
</script>

<style scoped lang='scss'>
::v-deep {
  .ql-editor {
    height: 200px;
  }
  .el-checkbox__label {
    margin-right: 30px;
  }
}
.opacity {
  opacity: 0;
}
.form-item {
  display: flex;
  justify-content: start;
  align-items: center;
  margin-bottom: 20px;
}
.uploadImg {
  margin-left: 4px;
  position: relative;
  width: 100px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  .imgbox {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 60px;
    z-index: 9;
  }
  .upload-progress{
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
  }
  span {
    width: 100px;
    height: 60px;
    position: absolute;
    top: 0;
    left: 0;
    font-size: 14px;
    z-index: 10;
  }
  .el-icon-circle-close {
    position: absolute;
    top: -10px;
    right: -10px;
    font-size: 18px;
    z-index: 11;
  }
}
</style>
